<template>
    <div class="users">
        <!-- 搜索 -->
        <el-input style="width:500px;margin-right:10px" v-model="search"></el-input>
        <el-button type="primary" @click="SearchValue()">
            <el-icon><Search /></el-icon>
        </el-button>
        <!-- 添加 -->
         <el-button type="primary" @click="addForm[0].show = true">添加用户</el-button>{{addForm.show}}
        <!-- 弹框 -->`
        <Dialog :dialog="addForm">
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="addForm[0].show = false">取消</el-button> 
                    <el-button type="primary" @click="add()">确定</el-button>
                </span>
            </template>
        </Dialog>
        <!-- 表格 -->
        <Table :cols="cols" :data="tableData"> 
            <!-- 状态 -->
            <template #switch="scope">
                    <el-switch
                        @change="change(scope.row)"
                        v-model="scope.row.mg_state"
                        class="ml-2"
                        style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
                    />
            </template>
            <!-- 操作 -->
            <template #action = "scope">
                <el-button type="primary" @click="open(scope.row)" :icon="Edit" circle />
                 <el-button type="danger" @click="del(scope.row)" :icon="Delete" circle />
                 <el-button type="warning" @click="Open(scope.row)" :icon="Setting" circle />
            </template>
        </Table>
        <!-- 修改弹框 -->
        <Dialog :dialog="changeForm">
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="changeForm[0].show = false">取消</el-button> 
                    <el-button type="primary" @click="changed()">确定</el-button>
                </span>
            </template>
        </Dialog>
        <!-- 角色弹框 -->
        <Dialog :dialog="rolesForm">
            <template #role>
                <el-form-item label="分配新角色" :label-width="formLabelWidth">
                    <el-select @change="changeRole" v-model="role.roleName" class="m-2" placeholder="Select">
                            <el-option
                            v-for="item in rolesForm[1].value"
                            :key="item.id"
                            :label="item.roleName"
                            :value="item.roleName"
                            />
                    </el-select>
                </el-form-item>
            </template>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="rolesForm[0].show = false">取消</el-button> 
                    <el-button type="primary" @click="selectRole">确定</el-button>
                </span>
            </template>
        </Dialog>
        <!-- 分页 -->
        <el-pagination
            v-model:currentPage="params.pagenum"
            v-model:page-size="params.pagesize"
            :page-sizes="[5, 10, 20, 30]"
            :small="small"
            :disabled="disabled"
            :background="background"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            />
    </div>
</template>
<script setup>
import Table from '@/components/Table.vue'
import Dialog from '@/components/Dialog.vue'
import { Search, Edit, Delete, Setting } from "@element-plus/icons-vue";
import { reactive, ref,onMounted,toRefs, activated } from 'vue'
import { getUsers, addUsers, changeSwitch, delUsers, changeUsers, searchUsers, setRoles } from '../../utils/users.js'
import { getRoles} from '../../utils/roles.js'
import { ElMessage,ElMessageBox } from 'element-plus'

// 列(表格)
const cols = [
    {
        title:'#',
        type:'index',
        align:'center',
        width:60
    },
    {
        title:'用户名',
        name:'username',
        align:'center'
    },
    {
        title:'邮箱',
        name:'email',
        align:'center'
    },
    {
        title:'电话',
        name:'mobile',
        align:'center'
    },
    {
        title:'角色',
        name:'role_name',
        align:'center'
    },
    {
        title:'状态',
        slot:'switch',
        align:'center'
    },
    {
        title:'操作',
        slot:'action',
        align:'center',
        width:200
    }
]
// 添加弹框
const addForm = ref([
    {
        show:false,
        title:'添加用户',
        data:ref([
            {
                name:'用户名',
                prop:'username',
                value:''
            },
            {
                name:'密码',
                prop:'password',
                value:''
            },
            {
                name:'邮箱',
                prop:'email',
                value:''
            },
            {
                name:'手机',
                prop:'mobile',
                value:''
            }
        ])
    },
    {   
        slot:'footer',
    }
])
// 修改弹框
const changeForm = ref([
    {
        show:ref(false),
        title:'修改用户',
        data:ref([
            {
                name:'用户名',
                prop:'username',
                value:'',
                disabled:true
            },
            {
                name:'邮箱',
                prop:'email',
                value:''
            },
            {
                name:'手机',
                prop:'mobile',
                value:''
            },
            {
                prop:'id',
                value:'',
                hide:true
            }
        ])
    },
    {   
        slot:'footer',
    }
])
// 角色弹框
const rolesForm = ref([
    {
        show:ref(false),
        title:'修改角色',
        data:ref([
            {
                name:'当前用户:',
                prop:'username',
                value:'',
                disabled:true
            },
            {
                name:'当前角色:',
                prop:'role_name',
                value:''
            },
            {
                prop:'id',
                value:'',
                hide:true
            }
        ])
    },
    {   
        name:'分配新角色',
        slot:'role',
        value:''
    },
    {   
        slot:'footer',
    }
])
const role = ref([]);
// 宽度
const formLabelWidth = '100px';
// 搜索
const search = ref('');
// 总条数
const total = ref(0);
// 分页
const params = reactive( {
    query:'',
    pagesize:5,
    pagenum:1
});
// 表格
const tableData = ref([]);
// 渲染
const getuserList = async ()=>{
    var {data:res} = await getUsers(params);
    total.value = res.total;
    tableData.value = res.users;
    console.log(201,res)
}
// 添加
const add = async ()=>{
    var form = {}; 
    addForm.value[0].data.map(item=>{
        // return `${item.prop}:${item.value}`
        return form[item.prop] = item.value
    })
     if(form.username == '' || form.password == '' || form.email == '' || form.mobile == ''){
        return ElMessage.warning('输入框不能为空');
    }
    // console.log(form,885)
    var data = await addUsers(form);
    if(data.meta.status == 201){
        ElMessage.success(data.meta.msg);
        addForm.value[0].show = false;
        // form.username = form.password = form.email = form.mobile = '';
        // form1.username = form1.password = form1.email = form1.mobile = '';
    }
    getuserList();
}
// 修改
const changed = async()=>{
    var form = {}; 
    changeForm.value[0].data.map(item=>{
        return form[item.prop] = item.value
    })
    console.log(form,885)
    let data = await changeUsers(form.id,form);
    console.log(data,'修改')
    if(data.meta.status == 200){
        ElMessage.success(data.meta.msg);
        changeForm.value[0].show = false;
        getuserList();
    }
}
//修改按钮
const open = (row)=>{              
    changeForm.value[0].show = true;
    changeForm.value[0].data.forEach(item=>{
        item.prop,Object.keys(row).forEach((it,i)=>{
            if(item.prop == it){
                item.value = Object.values(row)[i];
            }
        })
    });
}
//角色按钮
const Open = async (row)=>{              
    rolesForm.value[0].show = true;
    rolesForm.value[0].data.forEach(item=>{
        item.prop,Object.keys(row).forEach((it,i)=>{
            if(item.prop == it){
                item.value = Object.values(row)[i];
            }
        })
    });
    let {data:res} = await getRoles();
     rolesForm.value[1].value = res;
}
//角色切换
const changeRole = (val)=>{
    rolesForm.value[1].value.forEach(item=>{
        if(item.roleName == val){
            return role.value = item;
        }
    });
}
// 更改角色
const selectRole = async ()=>{
    var form = {}; 
    rolesForm.value[0].data.map(item=>{
        return form[item.prop] = item.value
    })
    var rid = role.value.id;
    let data = await setRoles(form.id,rid);
    if(data.meta.status == 200){
        ElMessage.success(data.meta.msg);
        rolesForm.value[0].show = false;
        getuserList();
    }
}
// 分页
const handleSizeChange = (val) => {
    params.pagesize = val;
    getuserList();
//   console.log(`${val} items per page`)
}
const handleCurrentChange = (val) => {
    params.pagenum = val;
    getuserList();
//   console.log(`current page: ${val}`)
}
// 搜索
const SearchValue= async ()=>{
    params.query = search.value;
    let {data:res} = await getUsers(params);
    tableData.value = res.users;
    // console.log(res);
}
// 修改状态
const change = async (row)=>{
    // console.log(row.mg_state)
    let data = await changeSwitch(row.id,row.mg_state);
    if(data.meta.status == 200){
        ElMessage.success(data.meta.msg)
    }
}
// 删除
const del = async (row)=>{
    ElMessageBox.confirm(
    `您确认删除【${row.username}】吗？删除后无法恢复`,
    '删除',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async () => {
        var data = await delUsers(row.id)
      ElMessage({
        type: 'success',
        message: data.meta.msg,
      })
      getuserList();
    }).catch(() => {})
}
onMounted(() => {
    getuserList();
})



</script>
<style lang="scss" scoped>
    
</style>